package com.lagou.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
//@Component //扫描到即生效
public class BlackListFilter implements GlobalFilter, Ordered {

    private static final List<String> blackList = Arrays.asList("0:0:0:0:0:0:0:1");

    /**
     * 过滤器核心方法
     *
     * @param exchange 封装了request和response对象的上下文
     * @param chain    网关过滤器链(包含全局过滤器和单路由过滤器)
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //ip
        String hostString = request.getRemoteAddress().getHostString();
        if (blackList.contains(hostString)) {
            //在黑名单中
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//状态码，未经授权
            log.debug("=====>IP:" + hostString + " 在黑名单中，将被拒绝访问!");
            String data = "Request be denied!";
            DataBuffer dataBuffer = response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
        //放行
        return chain.filter(exchange);
    }

    /**
     * 过滤器的执行顺序，正序
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
